import { defineStore } from "pinia";
import { getUserInfo } from '@/service/user';


export const useUserStore = defineStore('user', {
    state: () => ({
        userData: {
            cUserId: null,
            name: '',
            avatar: '',
            birthday: '',
            height: '',
            weight: '',
            birthplace: '',
            loveColor: '',
            lovePeople: '',
            loveFood: '',
            hobby: '',
            loveAnimals: '',
            taskCount: '',
            bookCount: ''
        }

    }),

    getters: {
        userInfo(state) {
            return { ...state };
        },
    },

    actions: {
        setUserData(data) {
            this.userData = data;
            localStorage.setItem('userData', JSON.stringify(data));
        },
        initializeStore() {
            const storedData = localStorage.getItem('userData');
            if (storedData) {
                this.userData = JSON.parse(storedData);
            }
        },
        async info() {
            const { data } = await getUserInfo();
            this.setUserData(data);
        },
        resetInfo() {
            this.$reset();
        },
    }
})


// 用于处理本地存储的辅助函数
function useStorage(key, defaultValue) {
    // 尝试从本地存储中获取数据
    const storedValue = localStorage.getItem(key);
    if (storedValue) {
        return JSON.parse(storedValue);
    }
    // 如果没有数据，则使用默认值
    return defaultValue;
}